<template>
  <div class="release">
    <div class="header">
      <Header></Header>
    </div>
    <div class="wrap">
      <el-form
        ref="formData"
        :rules="rules"
        :model="formItem"
        label-position="top"
      >
        <div class="title">
          <el-form-item label="标题" prop="title">
            <el-input
              placeholder="请输入标题"
              v-model="formItem.title"
              maxlength="30"
              show-word-limit
            >
            </el-input>
          </el-form-item>
        </div>
        <div class="content">
          <el-form-item label="说说你的感受" prop="content">
            <el-input
              type="textarea"
              placeholder="请输入内容"
              v-model="formItem.content"
              maxlength="1000"
              :rows="6"
              show-word-limit
            >
            </el-input>
          </el-form-item>
        </div>
        <div class="uploadImg">
          <el-form-item class="is-required" label="上传图片">
            <el-upload
              action="#"
              list-type="picture-card"
              :on-preview="handlePreview"
              :before-upload="handelBeforeUpload"
              :on-remove="handleRemove"
              :on-success="handleSuccess"
              accept="image/*"
              :multiple="true"
              :http-request="uploadHttpRequest"
              :on-change="onChange"
            >
              <i class="el-icon-plus"></i>
            </el-upload>
            <el-dialog :visible.sync="dialogVisible">
              <img width="100%" :src="dialogImageUrl" alt="" />
            </el-dialog>
          </el-form-item>
        </div>
        <div class="noteType">
          <div class="type-title required">请选择类型</div>
          <el-radio-group v-model="noteType">
            <el-radio-button
              v-for="(item, index) in typelist"
              :key="index"
              :label="item.id"
              >{{ item.title }}</el-radio-button
            >
          </el-radio-group>
        </div>
        <div class="submit" @click="submit">
          <el-button type="primary">发布</el-button>
        </div>
      </el-form>
    </div>
  <Footer></Footer>
  </div>
</template>
<script>
import Header from "../components/Header";
import Footer from "../components/Footer.vue";
export default {
  components: {
    Header,
    Footer
  },
  data() {
    return {
      typelist: [],
      noteType: "",
      formItem:{
        title:'',
        content:'',
      },
      rules:{
        title:[
        {required: true, message: '请输入标题', trigger: 'blur' }
        ],
        content:[{required: true, message: '请输入内容', trigger: 'blur' }],
      },
      dialogImageUrl:'',
      dialogVisible:false,
      loginVisible:false,
      imgUrl:'',
      fileList:[],
      imgList:[],
      userinfo:'',
      
    };
  },
  mounted(){
    this.id = this.$route.query.id;
    this.userinfo = JSON.parse(sessionStorage.getItem("userinfo"));
    
    this.getNewsTypes()
  },
  methods:{
    onChange(file,fileList){
      // console.log('fileList',fileList)
     this.fileList=fileList 
    },
    handelBeforeUpload(file){
       let fileName=file.name.substring(file.name.lastIndexOf('.')+1)
     let fileType = ".gif|.jpeg|.jpg|.png|.svg|";
      if (fileType.indexOf(fileName + "|") == "-1") {
        this.$message({
          type: "error",
          message: "不支持此格式文件上传"
        });
        return false
      } 
    
    },
    uploadHttpRequest(file){
      console.log('file',file)
       var formFile = new FormData();
        formFile.append('img',file.file);  
      this.$axios.post('upImage',formFile).then(res=>{
        this.imgUrl=res.data
        this.$message.success(res.msg)
       this.imgList=this.imgList.concat(res.data)
       console.log('imgList',this.imgList);
      }).catch(err=>{
        console.log('err',err);
      })
    },
    handleSuccess(response, file, fileList) {
      console.log(1111);
      /**
       * 当上传多个文件时,如果直接 $emit('success').
       * onSuccess 再进行 fileList.push(file).
       * 会报错 Uncaught TypeError: Cannot set property 'status' of null.
       */
      // console.log('fileList', response, file, fileList)
      var arr = []// eslint-disable-line no-unused-vars
      arr=fileList[fileList.length-1]={
        ...fileList[fileList.length-1],
        path:this.path
      }
     
      // console.log('fileList',fileList);
      setTimeout(() => {
        console.log('fileList', response, file, fileList)
      }, 1);
     
    },
    handlePreview(){
      this.dialogImageUrl = this.imgUrl;
      this.dialogVisible = true;
    },
    handleRemove(){

    },
    
    // 获取文章类型
    getNewsTypes() {
      this.$axios
        .get("getNewsTypes")
        .then((res) => {
          //  console.log(res,'res')
          if (res.code === 1) {
            this.typelist = res.data;
           
          }
        })
        .catch((err) => {
          console.log("err", err);
        });
    },
    submit(){
      if(!this.userinfo){
          this.$confirm('您还未登录, 是否登录?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            //点击确定的操作(调用接口)
            this.$router.push({name:'Login'})
          }).catch(() => {
            //几点取消的提示
          });
        
        return false
      }else{
        this.sendNote()
      }
      
    },
    sendNote(){
      if(this.imgList.length===0){
        this.$message.error('请上传图片')
        return false
      }
      if(!this.noteType){
        this.$message.error('请选择笔记类型')
        return false
      }
      this.$refs.formData.validate((valid) => {
          if (valid) {
            let params={
              token:this.token,
              title:this.formItem.title,
              type:this.noteType,
              editorValue:this.formItem.content,
              imgs:this.imgList,
              is_video:0
            }
            this.$axios.post('addNews',params).then(res=>{
                console.log('res',res);
                this.$message.success(res.msg)
                this.$router.push({name:'Home'})
            }).catch(err=>{
              console.log('err',err);
            })
          } else {
            console.log('请检查必填项');
            return false;
          }
        });
      }
    },
  
};
</script>
<style >
.noteType .el-radio-button {
    position: relative;
    display: inline-block;
    outline: 0;
    /* margin-right: 20px; */
}
.noteType .el-radio-button__orig-radio:checked+.el-radio-button__inner {
    color: #FFF;
    background-image: linear-gradient(219deg, #f78361 3%, #f54b64 100%);
    background-color:#f54b64;
    border-color: #f54b64;
    box-shadow: -1px 0 0 0 #f54b64;
}
</style>
<style lang="less" scoped>
.wrap {
  width: 1200px;
  margin: 20px auto;
  /deep/ .el-form-item__label {
    font-size: 16px;
    font-weight: 600;
  }
  .title {
    text-align: left;
    background: #fff;
    padding: 20px;
  }
  .content {
    text-align: left;
    margin-top: 20px;
    background: #fff;
    padding: 20px;
  }
  .uploadImg {
    background: #fff;
    text-align: left;
    margin-top: 20px;
    padding: 20px;
  }
  .noteType {
    display: flex;
    margin-top: 20px;
    background: #fff;
    padding: 20px;
    align-items: center;
    .type-title {
      margin-right: 20px;
    }
  }
  .type-title {
    font-size: 16px;
    font-weight: 600;
  }
  .required::before {
    content: '*';
    color: #F56C6C;
    margin-right: 4px;
}
  .submit {
    text-align: center;
    margin-top: 20px;
    padding: 20px;
    /deep/ .el-button--primary {
    background-color: #000;
    border-color: #000;
}
  }
}
.title-name {
  text-align: left;
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 10px;
}
</style>
